package com.xjc.infra.util;


import org.springframework.context.support.ResourceBundleMessageSource;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ResourceBundleMessageSourceExtend extends ResourceBundleMessageSource {

    private static final String ENCODING = "UTF-8";// 注意属性文件使用GBK编码

    /** cache the encoding key value * */
    Map<String, String> encodingCache = new ConcurrentHashMap<String, String>(20);

    /**
     * resolve no argus
     */
    protected String resolveCodeWithoutArguments(String code, Locale locale) {
	String message = super.resolveCodeWithoutArguments(code, locale);
	return decodeString(message, ENCODING);

    }

    /**
     * resolve args
     * 
     * @see resolveCode(String code, Locale locale)
     */
    protected MessageFormat createMessageFormat(String msg, Locale locale) {
	if (logger.isDebugEnabled()) {
	    logger.debug("Creating MessageFormat for pattern [" + msg + "] and locale '" + locale + "'");
	}
	msg = decodeString(msg, ENCODING);
	return new MessageFormat((msg != null ? msg : ""), locale);
    }

    /**
     * 转码
     * 
     * @param msg
     * @param encode
     * @return
     */
    private String decodeString(String message, String encode) {
	String encodMessage = encodingCache.get(message);
	if (encodMessage == null) {
	    try {
		encodMessage = new String(message.getBytes("ISO8859-1"), encode);
		encodingCache.put(message, encodMessage);
	    } catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	    }
	}
	return encodMessage;
    }

}